<?php

namespace App\Api\Http\Controllers\V1\In;

use App\Admin\Eloquent\GiftActivity;
use App\Admin\Eloquent\Project;
use App\Api\Eloquent\ProjectsUser;
use Ibeibeili\SinaPay\Facades\BindingVerify;
use Ibeibeili\SinaPay\Facades\QueryIsSetPayPassword;
use Ibeibeili\SinaPay\Facades\SetRealName;
use Ibeibeili\SinaPay\Facades\QueryBalance;
use Ibeibeili\SinaPay\Facades\CreateBatchHostingPayTrade;
use App\Admin\Eloquent\Information;
use App\Admin\Eloquent\ProjectProfit;
use App\Api\Eloquent\UserInfo;
use App\Api\Eloquent\User;
use Ibeibeili\SinaPay\Facades\UnbindingVerify;
use Illuminate\Http\Request;
use App\Api\Http\Controllers\Controller;
use App\Eloquent\TradeRecords;
use Hash;
use Illuminate\Support\Facades\Cache;
use DB;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller{
    /*
     * 账户管理
     */
    public function my(Request $request){
        $user=User::user();
        $user->id_card=null;
        $user->email=="" && $user->email=null;
        if($user->userInfo->id_card){
            $user->show_name=$user->userInfo->name;
            //隐藏身份证号码中间10位
            $user->id_card=substr_replace($user->userInfo->id_card,'**********',4,10);
        }
        elseif($user->username){
            $user->show_name=$user->username;
        }
        else{
            $user->show_name=substr_replace($user->phone_number,'****',3,4);
        }
        if($user->phone_number){
            //隐藏手机号码中间4位
            $user->R_phone_number=substr_replace($user->phone_number,'****',3,4);
        }
        if($user->userInfo->bank_card_id==null){
            $user->bind_bank=false;
        }
        else{
            $user->bind_bank=true;
        }
        if($user->email_verified==1){
            $user->email=substr_replace($user->email,'****',3,4);
        }
        //如果本地未设置支付密码
        if($user->userInfo->is_set_pay_password==0){
            $user->spp=false;
        }
        else{
            $user->spp=true;
        }
        return $this->my_jsonp($request->input('callback'),compact('user'));
    }
    /*
     * 修改登录密码
     */
    public function editPIn(Request $request){
        $data=$request->UserData;

//        //验证原密码和新密码是否相同
//        if($password!=$password){
//            //验证两次新密码是否相同
//            if($request->n_password==$request->n_rpassword){
                $user=User::user();
                $res=User::where('id','=',$user->id)
                    ->first();
                if(Hash::check($data['passwordP'],$res->password)){
                    if(User::where('id','=',$user->id)
                        ->update(['password'=>bcrypt($data['passwordT'])])){
                        session()->flush();
                        session()->regenerate();
                        return $this->my_jsonp($request->input('callback'),'',906);//修改密码成功
                    }
                    return $this->my_jsonp($request->input('callback'),'',630);//修改失败
                }
                else{
                    $message='原密码不正确';
                    return $this->my_jsonp($request->input('callback'),'',621,$message);//原密码不正确
                }
//            }
//            else{
//                //输入两次密码不相同
//                $my_status='';
//                return $this->my_jsonp($request->input('callback'),'',$SID,$my_status);
//            }
//        }
//        else{
//            //新密码不能和原密码相同
//            $my_status='';
//            return $this->my_jsonp($request->input('callback'),'',$SID,$my_status);
//        }
    }
    /*
     * 设置手势密码
     */
    public function createHand(Request $request){

    }
    /*
     * 修改手势密码
     */
    public function editHand(Request $request){

    }
    /*
     * 确认原绑定手机
     */
    public function bindPhone(Request $request){
        $data=$request->UserData;

        $user=User::user();
        if(empty($data['code'])){
            if(Cache::has('api_'.$user->phone_number.'send')){
                return $this->my_jsonp($request->input('callback'),'',603,'请勿重复发送');
            }
//            return $this->my_jsonp($request->input('callback'));
            $str = rand(100000, 999999);
            //取短信信息模板
            $message = Information::where('type', 'information_sms')//短信模板
            ->where('position', '=', 'sms_address_code')//验证码位置的短信模板
            ->where('state', 1)//启用
            ->first();
            //合成短信
            $to_message = str_replace('{code}', $str, $message->content);
            $result=phone_code($user->phone_number,$to_message);
            if($result){
                Cache::put('api_'.$user->phone_number, $str, 5);
                Cache::put('api_'.$user->phone_number.'send',true,0.5);
                return $this->my_jsonp($request->input('callback'));
            }
            return $this->my_jsonp($request->input('callback'),'',605);//手机验证码发送失败
        }
//        $r_code='654321';
        if(Cache::has('api_'.$user->phone_number)){
            $r_code=Cache::get('api_'.$user->phone_number);
        }
        else{
            return $this->my_jsonp($request->input('callback'),'',602);//验证码已失效
        }
        if($data['code']!=$r_code){
            return $this->my_jsonp($request->input('callback'),'',601); //手机验证码错误
        }
        Cache::forget('api_'.$user->phone_number);
        return $this->my_jsonp($request->input('callback'));
    }
    /*
     * 修改绑定手机
     */
    public function editPhone(Request $request){
        $data=$request->UserData;
        $validator = Validator::make($data, [
            'phone_number'=>array('digits:11','regex:/^0?1[3-9]\d{9}$/'),
            'Veri_code'=>'digits:6',
        ],[
            'phone_number.digits'=>'手机号码格式有误',
            'Veri_code.digits'=>'验证码格式有误',
            'regex'=>'请输入正确的手机号码',
        ]);
        if($validator->fails()){
            $v_message=$validator->errors();
            if($v_message->has('phone_number')){
                return $this->my_jsonp($request->input('callback'),'',899,$v_message->first('phone_number'));//输入信息不符合规则
            }
            if($v_message->has('Veri_code')){
                return $this->my_jsonp($request->input('callback'),'',899,$v_message->first('yanzm'));//输入信息不符合规则
            }
        }
        if(User::where('phone_number',$data['phone_number'])->exists()){
            return $this->my_jsonp($request->input('callback'),'',721,'该手机号已认证');//该手机号已认证
        }
        if(empty($data['Veri_code'])){
            if(Cache::has('api_'.$data['phone_number'].'send')){
                return $this->my_jsonp($request->input('callback'),'',603,'请勿重复发送');
            }
//            return $this->my_jsonp($request->input('callback'));
            $str = rand(100000, 999999);
            //取短信信息模板
            $message = Information::where('type', 'information_sms')//短信模板
            ->where('position', '=', 'sms_address_code')//验证码位置的短信模板
            ->where('state', 1)//启用
            ->first();
            //合成短信
            $to_message = str_replace('{code}', $str, $message->content);
            //接收的手机号
            $result=phone_code($data['phone_number'],$to_message);
//        $result=null;
            if($result){
                Cache::put('api_'.$data['phone_number'], $str, 5);
                Cache::put('api_'.$data['phone_number'].'send',true,0.5);
                return $this->my_jsonp($request->input('callback'));
            }
            return $this->my_jsonp($request->input('callback'),'',605);//验证码发送失败
        }
//        $r_code='654321';
        if(Cache::has('api_'.$data['phone_number'])){
            $r_code=Cache::get('api_'.$data['phone_number']);
        }
        else{
            return $this->my_jsonp($request->input('callback'),'',602);//验证码已失效
        }
        if($data['Veri_code']!=$r_code){
            return $this->my_jsonp($request->input('callback'),'',601);//手机验证码错误
        }
        Cache::forget('api_'.$data['phone_number']);

        $user=User::user();
        $pay_password_result= QueryIsSetPayPassword::send(['identity_id' => $user->identity_id, 'identity_type' => 'UID']);
        //如果已设置支付密码
        if($pay_password_result['is_set_paypass'] == 'Y') {
            return $this->my_jsonp($request->input('callback'),'',721,'你已设置支付密码，请联系客服进行修改绑定手机');
            $user->userInfo->is_set_pay_password = 1;
            $user->userInfo->save();
            //设置支付密码的修改绑定手机
        }
        //如果已绑定手机
        if($user->phone_number_verified==1){
            $to_result=UnbindingVerify::send(['identity_id'=>$user->identity_id,'identity_type'=>'UID','verify_type'=>'MOBILE']);
            if($to_result['response_code']!='APPLY_SUCCESS'){
                empty($to_result['response_message']) && $to_result['response_message']='系统繁忙,请稍后再试';
                return $this->my_jsonp($request->input('callback'),'',721,$to_result['response_message']);//手机认证失败
            }
        }
        $result=BindingVerify::send(['identity_id'=>$user->identity_id,'verify_type'=>'MOBILE','verify_entity'=>$data['phone_number']]);
        if($result['response_code']!='APPLY_SUCCESS'){
            empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
            return $this->my_jsonp($request->input('callback'),'',721,$result['response_message']);//手机认证失败
        }
        if(User::where('id',$user->id)->update(['phone_number'=>$data['phone_number'],'phone_number_verified'=>1])){
            $user->phone_number=$data['phone_number'];
            $user->phone_number_verified=1;
            return $this->my_jsonp($request->input('callback'),'',901);//手机认证成功
        }
        return $this->my_jsonp($request->input('callback'),'',600);
    }
    /*
     * 绑定邮箱
     */
    public function bindEmail(Request $request,$email){
        if(User::where('email','=',$email)->exists()){
            return $this->my_jsonp($request->input('callback'),'',722);//认证失败,该邮箱已认证
        }
        $user=User::user();
        if(!$user->sendEmailBindLink($email)){
            return $this->my_jsonp($request->input('callback'),'',725);//邮箱验证码发送失败
        }
        return $this->my_jsonp($request->input('callback'),'',905);
    }
    /*
     * 修改绑定邮箱
     */
    public function editEmail(Request $request,$email,$n_email){
        $user=User::user();
        $r_email=User::where('id',$user->id)->value('email');
        if($r_email!=$email){
            return $this->my_jsonp($request->input('callback'),'',724);//原邮箱不正确
        }
        if(User::where('email','=',$email)->exists()){
            return $this->my_jsonp($request->input('callback'),'',722);//认证失败,该邮箱已认证
        }
        $user->sendEmailBindLink($n_email);
        return $this->my_jsonp($request->input('callback'));
    }
    /*
     * 实名认证
     */
    public function certification(Request $request){
        $data=$request->UserData;
        $validator = Validator::make($data, [
            'Uname'=>array('regex:/^([\x80-\xff]+)$/'),
            'Uid'=>array('regex:/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/'),
        ],[
            'Uname.regex'=>'姓名必须为中文',
            'Uid.regex'=>'身份证格式错误',
        ]);
        if($validator->fails()){
            $v_message=$validator->errors();
            if($v_message->has('Uname')){
                return $this->my_jsonp($request->input('callback'),'',899,$v_message->first('Uname'));//输入信息不符合规则
            }
            if($v_message->has('Uid')){
                return $this->my_jsonp($request->input('callback'),'',899,$v_message->first('Uid'));//输入信息不符合规则
            }
        }
        $user=User::user();
        if(UserInfo::where('id_card','=',$data['Uid'])->exists()){
            return $this->my_jsonp($request->input('callback'),'',712);//该实名已被认证
        }
        if($user->userInfo->name_verified==1){
            return $this->my_jsonp($request->input('callback'),'',710);//该用户已实名认证
        }
        $result=SetRealName::send(['identity_id'=>$user->identity_id,'real_name'=>$data['Uname'],'cert_no'=>$data['Uid']]);
        if($result['response_code']=='DUPLICATE_VERIFY'){
            return $this->my_jsonp($request->input('callback'),'',710);//该用户已实名认证
        }
        elseif($result['response_code']=='ILLEGAL_ARGUMENT'){
            return $this->my_jsonp($request->input('callback'),'',711);//请输入正确的身份证号码
        }
        elseif($result['response_code']=='APPLY_SUCCESS'){
            DB::beginTransaction();
            try{
                $user_info=UserInfo::findOrFail($user->id);
                //真实姓名
                $user_info->name=$data['Uname'];
                //身份证号码
                $user_info->id_card=$data['Uid'];
                $user_info->name_verified=1;
                $user_info->save();
                $user->userInfo->name=$data['Uname'];
                $user->userInfo->id_card=$data['Uid'];
                $user->userInfo->name_verified=1;
                DB::commit();
            }
            catch (Exception $e){
                DB::rollback();
                return $this->my_jsonp($request->input('callback'),'',600,$e->getMessage());
            }
            return $this->my_jsonp($request->input('callback'),'',902);//实名认证成功
        }
        empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
        return $this->my_jsonp($request->input('callback'),'',600,$result['response_message']);
    }
    /*
     * 钱包管理
     */
    public function wallet(Request $request){
        $user=User::user();

        $params['identity_id']=$user->identity_id;
        $params['identity_type']='UID';
        $params['account_type']='SAVING_POT';
        $result=QueryBalance::send($params);
        if($result['response_code']=='NO_BASIC_ACCOUNT'){
            $money=array();
            //展示数据
            $money['have']='0.00';//持有总资产
            $money['canuse']='0.00';//可用余额
            $money['willcorpus']='0.00';//待收本金
            $money['willprofit']='0.00';//待收收益
            $money['frostmoney']='0.00';//冻结金额
            $money['allprofit']='0.00';//总收益
            $money['invest']='0.00';//总投资
            $money['profit']='0.00';//已收收益
            //画图数据
            $money['r_canuse']='0.00';//可用余额
            $money['r_willcorpus']='0.00';//待收本金
            $money['r_willprofit']='0.00';//待收收益
            $money['r_frostmoney']='0.00';//冻结金额
        }
        elseif($result['response_code']=='SYSTEM_ERROR'){
            empty($result['response_message']) && $result['response_message']='系统繁忙,请稍后再试';
            return $this->my_jsonp($request->input('callback'),'',600,$result['response_message']);
        }
        else{
            $r_user_profit=ProjectProfit::where('user_id','=',$user->id)->get();
            $user_profit=$r_user_profit->groupBy('status');
            $money['r_canuse']=$result['available_balance'];//可用余额
            $money['r_willcorpus']=empty($user_profit['0'])?'0.00':collect($user_profit['0'])->sum('money');//待收本金
            $money['r_willprofit']=empty($user_profit['0'])?'0.00':collect($user_profit['0'])->sum('profit');//待收收益
            $money['r_frostmoney']=$result['balance']-$result['available_balance'];//冻结金额

            $money['canuse']=number_format($money['r_canuse'],2);//可用余额
            $money['willcorpus']=number_format($money['r_willcorpus'],2);//待收本金
            $money['willprofit']=number_format($money['r_willprofit'],2);//待收收益
            $money['frostmoney']=number_format( $money['r_frostmoney'],2);//冻结金额
            $money['have']=number_format($result['available_balance']+$money['r_willcorpus']+$money['r_willprofit'],2);//持有资产
            $money['allprofit']=empty($r_user_profit)?'0.00':number_format(collect($r_user_profit)->sum('profit'),2);//总收益
            $money['invest']=empty($r_user_profit)?'0.00':number_format(collect($r_user_profit)->sum('money'),2);//总投资
            $money['profit']=empty($user_profit['1'])?'0.00':number_format(collect($user_profit['1'])->sum('profit'),2);//已收收益
        }
        return $this->my_jsonp($request->input('callback'),compact('money'));
    }
    /*
     * 邀请页面
     */
    public function invite(Request $request,$page){
        $user=User::user();
        $invite_code=$user->userInfo->invite_code;
        //被邀请人的详细信息
        $a=10;
        $invite=UserInfo::join('users','id','=','user_id')
            ->where('recommended','=',$user->id)
            ->orderBy('created_at','desc')
            ->skip($a*$page)
            ->limit($a)
            ->select('users.phone_number','users.username','user_info.*')
            ->get();
        if($invite->count()){
            foreach($invite as $inviter){
                $inviter_id[]=$inviter->user_id;
                $inviter_money[$inviter->user_id]=array();
            }
            $status=array('payment','finish','late');
            $users_invite=ProjectsUser::join('projects','projects.id','=','projects_user.projects_id')
                ->whereIn('projects_user.user_id',$inviter_id)
                ->whereIn('projects.status',$status)
                ->select('projects_user.*')
                ->get();
            foreach($users_invite as $user_invite){
                $inviter_money[$user_invite->user_id][$user_invite->id]=$user_invite->invest_money;
            }
            foreach($inviter_money as $key1=> $money){
                $inviter_money[$key1]=collect($money)->sum();
            }

            foreach($invite as $key2=> $inviter){
                $inviter->invite_money=number_format($inviter->invite_money,2);
                $inviter->name=$inviter->name?$inviter->name:($inviter->phone_number?$inviter->phone_number:$inviter->username);
                $inviter->time=substr($inviter->created_at,0,10);
                $inviter->use_money=number_format($inviter_money[$inviter->user_id],2);
                $invite[$key2]=$inviter;
            }
        }
        $invite_url=$this->getNowUrl().'/weixin/html/Ucenter/register.html?invite_code='.$invite_code;
        $invites= view('api.invite',compact('invite'))->__toString();
        return $this->my_jsonp($request->input('callback'),compact('invites','invite_code','invite_url'));
    }
//    /*
//     * 生成邀请链接
//     */
//    public function createInviteUrl(Request $request){
//        $user=User::user();
//        $invite_code=$user->userInfo->invite_code;
//        $invite_url='https:mobile.ibeibeili.com/bbl/html/Ucenter/register.html?invite_code='.$invite_code;
//        return $this->my_jsonp($request->input('callback'),compact('invite_url'));
//    }
}